# -*- coding: utf-8 -*-
"""
===============================
@Author     : Zuo WenTao
@Time       : 2024/11/29 9:54
@Description: 
@Change     : 
@File       : SendToWx.py
===============================
"""
import sys
import platform


if platform.system().lower() == 'linux':
    sys.path.append("/home/zuo/26_DocumentDelivery/")
from collections import defaultdict
from datetime import timedelta, datetime

import requests
from jmespath.ast import projection
from loguru import logger

from Api.mongo_client import mongo_client2


def get_previous_and_next_day(date_str):
    current_date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")

    previous_day_midnight = current_date - timedelta(days=1, hours=current_date.hour, minutes=current_date.minute, seconds=current_date.second)

    next_day_midnight = current_date + timedelta(days=0, hours=current_date.hour, minutes=current_date.minute, seconds=current_date.second) - timedelta(seconds=1)

    previous_day_midnight_str = previous_day_midnight.strftime("%Y-%m-%d")
    next_day_midnight_str = next_day_midnight.strftime("%Y-%m-%d")

    return previous_day_midnight_str, next_day_midnight_str


def send_to_wx(key):
    date_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    previous_day_midnight, next_day_midnight = get_previous_and_next_day(date_str)
    # previous_day_midnight, next_day_midnight = '2024-11-21', '2024-12-03'
    projection = {"_id": 0, "status": 1, "error_msg": 1}
    query = {"$and": [{"create_date": {"$gte": previous_day_midnight}}, {"create_date": {"$lt": next_day_midnight}}]}
    document_bool, document_data = mongo_client2.find_document("DocumentDeliveryTask", query, projection=projection, Type=2)
    document_data = list(document_data)
    total_num = len(document_data)
    # total_num = 759

    grouped_data = defaultdict(list)

    for doc in document_data:
        msg = doc.get('error_msg', '')
        if msg == "IP被封禁": continue
        status = doc.get('status', '')
        if status == 0: continue
        grouped_data[status].append(doc)

    grouped_data = {key: list(value) for key, value in grouped_data.items()}
    # input(grouped_data)

    massages = []
    status_msg = {1: "文献传递成功", 2: "文献传递中", -1: "未检索到文献", -2: "文献传递失败"}
    massages.append(f">\t\t今日文献传递总量 ：<font color=\"info\">{total_num} 篇</font>\n")
    for key, value in grouped_data.items():
        massages.append(f">\t\t{status_msg[key]} ：<font color=\"info\">{len(value)} 篇</font>\n")

    success_num = len(grouped_data.get(1, [])) + len(grouped_data.get(2, []))
    fail_num = len(grouped_data.get(-1, [])) + len(grouped_data.get(-2, []))
    massages.append(f">\t\t今日文献传递成功率 ：<font color=\"info\">{success_num / (success_num + fail_num) * 100:.2f}%</font>\n")

    rule_str = "".join(massages)

    print(rule_str)

    # webhook_url = f'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={key}'  # 定时任务推送群
    # webhook_url = f'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={key}'  # 定时任务推送群
    webhook_url = f'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={key}'  # 定时任务推送群
    data = {
        "msgtype": "markdown",  # 消息类型，此时固定为markdown
        "markdown": {
            "content": "# **提醒 中文书_百链文献传递**\n"
        }}
    data["markdown"]["content"] += rule_str

    header = {'Content-Type': 'application/json'}

    try:
        respon = requests.post(webhook_url, headers=header, json=data)
        logger.info(f"Webhook推送结果通知 {respon.json()}")
    except Exception as e:
        logger.error(f"Webhook 推送结果失败通知 {e}")
    logger.info('今日更新结束')


if __name__ == '__main__':
    # send_to_wx('b62e3520-9532-45a5-847c-d848aa80161c')
    send_to_wx('aa31e416-6a0a-4dd9-bff9-6e9e5e97d50b')

"""
>		今日文献传递总量 ：<font color="info">41 篇</font>
>		未检索到文献 ：<font color="info">41 篇</font>
>		今日文献传递成功率 ：<font color="info">0.00%</font>
"""